package com.example.hotel_demo.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Arrays;

@Component
@Aspect
public class LoginIntercept {
    private static final Logger logger = LoggerFactory.getLogger(LoginIntercept.class);

    //@Pointcut("execution(public * com.example.hotel_demo.controller.Intercept.*(..))")
    @Pointcut("within(com.example.hotel_demo.controller..*) && !within(com.example.hotel_demo.controller.LoginCheckController)" +
            "&& !within(com.example.hotel_demo.controller.GetLoginCodeController) " +
            "&& !within(com.example.hotel_demo.controller.RegistController)")
    public void webLog(){
        System.out.println("begin");
    }


    @Around("webLog()")
    public Object trackInfo(ProceedingJoinPoint pjp) throws Throwable {
        HttpSession session= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();

        String username = (String) session.getAttribute("username");
        if(username == null) {
            logger.info("-------------没有登录-------------");
            return new ModelAndView("redirect:/login-go");
        }
        logger.info("username: " + username);
        return pjp.proceed();
    }
/**
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("RESPONSE : " + ret);
    }
**/
}
